﻿function ApartmentGallery() {
    this.GalleryHandler = $('#apartmentGalleryContent');
    this.LeftArrow = $('#apartmentGallery .left');
    this.RightArrow = $('#apartmentGallery .right');
    var items = new Array();
    this.GalleryHandler.find('a').each(function () {
        var photo = new GalleryPhoto($(this).attr('href'), $(this).attr('data-category'), $(this).attr('title'));
        items.push(photo);
    });
    this.Items = items;
    this.PhotoWidth = this.GalleryHandler.width();
    this.GalleryHandler.html('');
    this.CurrentPhotoIndex = 0;
    this.ShowPhoto(this.Items[0]);

    var g = this;
    this.LeftArrow.click(function () { g.ShowPrev(); });
    this.RightArrow.click(function () { g.ShowNext(); });
    $(window).resize(function () {
        g.PhotoWidth = g.GalleryHandler.width();
        g.ReInit();
    });
}

ApartmentGallery.prototype.ShowPhoto = function (photo) {
    this.GalleryHandler.find('img').remove();
    this.LeftArrow.hide();
    this.RightArrow.hide();
    var g = this;
    var $img = $('<img />');
    $img.css('visibility', 'hidden');
    $img.load(function () {
        g.GalleryHandler.append($img);
        g.GalleryHandler.animate({ height: $img.height() + 'px' }, 'slow', function () {
            $img.hide().css({ visibility: 'visible' }).fadeIn(500, function () {
                g.LeftArrow.show();
                g.RightArrow.show();
            });
        });
    }).attr('src', photo.PhotoSrc.replace('1000x1000', g.PhotoWidth + 'x1000'));
}

function GalleryPhoto(url, category, title) {
    this.PhotoSrc = url;
    this.Category = category;
    this.Title = title;
}

ApartmentGallery.prototype.ShowNext = function () {
    this.CurrentPhotoIndex = this.CurrentPhotoIndex + 1;
    if (this.CurrentPhotoIndex >= this.Items.length) this.CurrentPhotoIndex = 0;
    this.ShowPhoto(this.Items[this.CurrentPhotoIndex]);
}

ApartmentGallery.prototype.ShowPrev = function () {
    this.CurrentPhotoIndex = this.CurrentPhotoIndex - 1;
    if (this.CurrentPhotoIndex <= 0) this.CurrentPhotoIndex = this.Items.length - 1;
    this.ShowPhoto(this.Items[this.CurrentPhotoIndex]);
}

ApartmentGallery.prototype.ReInit = function () {
    this.ShowPhoto(this.Items[this.CurrentPhotoIndex]);
}

$(function () {
    new ApartmentGallery();
});